using System;
using System.Collections.Generic;
using System.IO;

namespace Gloom
{
	public class UntranslatedGLFunc
	{
		public readonly string Name;
		public readonly string Version;
		public readonly string ReturnType;
		public readonly Dictionary<string, string> ParamsNameType = new Dictionary<string, string>();
		
		private UntranslatedGLFunc(string name, string version, string returnType, Dictionary<string, string> args)
		{
			Name = name;
			Version = version;
			ReturnType = returnType;
			ParamsNameType = args;
		}
		
		public override string ToString ()
		{
			string s = "Name: " + Name + " Version: " + Version + " ReturnType `" + ReturnType + "' ParamsNameType ";
			foreach (KeyValuePair<string, string> kvp in ParamsNameType)
				s += "[`" + kvp.Key + "',`" + kvp.Value + "'] ";
			return s;
		}
		
		public static UntranslatedGLFunc Parse(List<string> block, StreamWriter infoLog, StreamWriter failLog)
		{
			string name = "", version = "", returnType = "";
			Dictionary<string, string> args = new Dictionary<string, string>();
			
			// Parse!
			
			// Line 0: FuncName(some, parameter, names)
			name = block[0].Substring(0, block[0].IndexOf('('));
			
			infoLog.WriteLine("UntranslatedGLFunc Name " + name);
			
			int ignored = 0;
			
			foreach (string l in block)
			{
				if (l[0] == '\t')
				{
					string[] bits = l.Split(new char[] { '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
					
					switch (bits[0])
					{
						case "return":
							if (bits.Length < 2 || bits.Length > 3)
								throw new Exception("Unexpected string bits count in UntranslatedGLFunc.Parse (raw line is `" + l + "'), expected 2 or 3");
							returnType = bits[1];
							infoLog.WriteLine("UntranslatedGLFunc ReturnType " + bits[1]);
							break;
						
						case "param":
							if (bits.Length < 5)
								throw new Exception("Unexpected string bits count in UntranslatedGLFunc.Parse (raw line is `" + l + "'), expected 5+");
							args.Add(bits[1], bits[2] + " " + bits[3] + " " + bits[4]);
							infoLog.WriteLine("UntranslatedGLFunc ParamsNameType Name: " + bits[1] + " Type: " + args[bits[1]]);
							break;
							
						case "version":
							if (bits.Length != 2)
								throw new Exception("Unexpected string bits count in UntranslatedGLFunc.Parse (raw line is `" + l + "'), expected 2");
							version = bits[1];
							infoLog.WriteLine("UntranslatedGLFunc Version " + version);
							break;
						
						default:
							ignored++;
							break;
					}
				}
			}
			
			infoLog.WriteLine("UntranslatedGLFunc Ignored " + ignored.ToString() + " other lines from this func block.");
			
			// Create the UGF.
			if (name == "")
				throw new Exception("Failed to parse name!");
			if (returnType == "")
				throw new Exception("Failed to parse returnType!");
			return new UntranslatedGLFunc(name, version, returnType, args);
		}
	}
}

